<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%-- <%@ taglib prefix="c"uri="http://java.sun.com/jstl/core" %> --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

 <%@ include file="/common/common.jsp" %>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>结算列表</title>
    <link href="${ctx}/static/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/dist/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/plugins/datatables/css/matrix-style.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/dist/css/AdminLTE.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/plugins/datatables/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/plugins/layer/skin/default/layer.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/plugins/validationEngine/css/validationEngine.jquery.css" rel="stylesheet" type="text/css">
    <script src="${ctx}/static/plugins/jQuery/jQuery-2.1.4.min.js"></script>
    <style>
        button.searching{
            background-color:#666
        }
        * {
            margin: 0;
            padding: 0;
        }

        body, button, input, select, textarea {
            font: 14px/1.5 tahoma, '微软雅黑 Regular', '微软雅黑';
        "\5b8b\4f53";
            -ms-overflow-style: scrollbar;
        }

        a, a:hover {
            text-decoration: none;
        }

        .content {
            width: 100%;
            margin: auto;
        }

        .content_about, .content_list {
            width: 96%;
            margin: auto;
        }

        .content_about {
            min-height: 300px;
            padding-bottom: 60px;
            color: #666;
        }

        .order-address {
            margin-top: 90px;
            width: 700px;
        }

        .order-address h2, .order-list h2 {
            margin-bottom: 30px;
            line-height: 25px;
            color: #333;
            font-weight: 700;
            font-size: 20px;
        }

        ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .address-wrap:hover {
            background-color: #fff0e8;
        }

        .order-address .address-wrap .address-list li {
            position: relative;
            line-height: 25px;
            padding-left: 92px;
            border: 1px solid #fff;
        }

        .selected {
            border-color: #f40;
            background-color: #fff0e8;
            margin: 5px 0 7px;
            line-height: 32px;
            box-shadow: 5px 5px 0 #f3f3f3;
        }

        .addressBox {
            margin-left: 10px;
            margin-bottom: 10px;
        }

        .addressInfo {
            display: inline-block;
            color: #3c3c3c;
            vertical-align: baseline;
        }

        .address-list li label em {
            color: grey;
            font-size: 14px;
            font-weight: 700;
            font-style: normal;
        }

        .btn-bar {
            margin-top: 24px;
        }

        .btn-bar .newAddrBtn {
            margin-left: 28px;
            width: 112px;
            height: 30px;
            display: inline-block;
            text-indent: 6px;
            vertical-align: text-top;
            background: #337ab7;
            line-height: 26px;
            border: 1px solid #2e6da4;
            border-radius: 6px;
            color: white;

        }

        .btn-bar .newAddrBtn:hover {
            background: #286090;
            color: white;
        }

        .addr_form {
            width: 809px;
            height: 400px;
            margin: auto;
        }

        .red {
            color: red;
        }

        .edit_btn {
            text-align: center;
            margin-top: 40px;
        }
        
        
    </style>
</head>
<body>
<div class="content">
<!--   收货地址开始 by  yyg -->
    <div class="content_about">
        <div class="order-address " id="address_1">
            <h2>选择收货地址</h2>
            <ul class="address-list" id="addressUl">
<!--             addressList -->
			<c:forEach items="${addressList}"  var="address"  varStatus="status">
                <li class="address-wrap">
                    <div class="addressBox">
                        <label class="addressInfo" for="addressInput${status.index+1}">
                            <input type="radio"    class="radioSelect"   onclick="change(${status.index+1});"  value="${address.id}" name="address" id="addressInput${status.index+1}">
                            		<c:if test="${address.isDefault==1}">
                        				<script type="text/javascript">
                        				$("input[name='address'][id='addressInput${status.index+1}']").attr("checked",true);
                        				$("input[id='addressInput${status.index+1}'][name='address']").parent().parent().parent().siblings().removeClass("selected");
                        			    $("input[id='addressInput${status.index+1}'][name='address']").parent().parent().parent().addClass("selected");;
                        				</script>	
                        			</c:if>
                            <span class="user-address">
                                <span >${address.provinceName}&nbsp;&nbsp;${address.cityName}&nbsp;&nbsp;${address.areaName}</span>
                                <span>${address.address}</span>
                                <span>（</span>
                                <span>${address.contacts}</span>
                                <span> 收）</span>
                                <em>${address.telPhone}</em>
                            </span>
                        </label>
                    </div>
                </li>
			</c:forEach>
            </ul>
            <div class="btn-bar">
                <a id="addAddr" class="newAddrBtn"  onclick="opneHiddenDiv();" href="javascript:void(0);">
                    <i class="fa fa-plus-square space" style="padding-right: 6px;"></i>使用新地址
                </a>
            </div>
        </div>
    </div>
    <!--   收货地址结束 by  yyg -->
    <hr>
    <form>
        <div class="content_list">
        <div class="order-list">
            <c:forEach items="${productList}" var="product" varStatus="status">
                <table class="table table-striped table-bordered table-hover" id="table_list${status.index+1}">
                    <h2>${product.supplierName}</h2>
                    <input type="hidden" class="supplierId"  value="${product.supplierId}">
                    <thead>
                    <tr role="row">
                        <th data-name="id">编号</th>
                        <th data-name="">商品名称</th>
                        <th data-name="">商品条码</th>
                        <th data-name="">商品总量</th>
                        <th data-name="">商品数量</th>
                        <th data-name="">单价</th>
                        <th data-name="">总额</th>
                    </tr>
                    </thead>
                    <tbody>
                        <c:forEach items="${product.phProductVoList}" var="productVo" varStatus="productStatus">
                            <tr>
                                <td>${productStatus.index+1}<input type="hidden" value="${productVo.id}"></td>
                                <td>${productVo.productName}</td>
                                <td>${productVo.barCode}</td>
                                <td>${productVo.productCount}</td>
                                <td>
                                    <c:choose>
                                        <c:when test="${roleCode  eq 6}">
                                            <span style="padding-right:10px;cursor:pointer"  onclick="removeCount('${productVo.sellerbAtchQuantity}','table_list${status.index+1}','totalPrice${productStatus.index+1}','count${productStatus.index+1}','${productVo.purchasePrice}')">-</span>
                                            <!--商戶起售數量-->
                                            <input style="width: 30px;" class="count${productStatus.index+1}" value="${productVo.sellerbAtchQuantity}"
                                                   onchange="validateCount('${productVo.sellerbAtchQuantity}','${productVo.productCount}',this,'table_list${status.index+1}','totalPrice${productStatus.index+1}','${productVo.purchasePrice}')"
                                                   onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                                                   onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}" />
                                            <span style="padding-left: 10px;cursor:pointer" onclick="addCount('${productVo.productCount}','table_list${status.index+1}','totalPrice${productStatus.index+1}','count${productStatus.index+1}','${productVo.purchasePrice}')">+</span>
                                        </c:when>
                                        <c:when test="${roleCode  eq 3}">
                                            <!--市級代理商起售數量-->
                                            <span style="padding-right:10px;cursor:pointer"  onclick="removeCount('${productVo.municipalBatchQuantity}','table_list${status.index+1}','totalPrice${productStatus.index+1}','count${productStatus.index+1}','${productVo.settlementPrice}')">-</span>
                                            <input style="width: 30px;" class="count${productStatus.index+1}" value="${productVo.municipalBatchQuantity}"
                                                   onchange="validateCount('${productVo.municipalBatchQuantity}','${productVo.productCount}',this,'table_list${status.index+1}','totalPrice${productStatus.index+1}','${productVo.settlementPrice}')"
                                                   onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                                                   onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}" />
                                            <span style="padding-left: 10px;cursor:pointer" onclick="addCount('${productVo.productCount}','table_list${status.index+1}','totalPrice${productStatus.index+1}','count${productStatus.index+1}','${productVo.settlementPrice}')">+</span>
                                        </c:when>
                                    </c:choose>
                                </td>
                                <td>
                                    <c:choose>
                                        <c:when test="${roleCode  eq 6}">${productVo.purchasePrice}</c:when>
                                        <c:when test="${roleCode  eq 3}">${productVo.settlementPrice}</c:when>
                                    </c:choose>

                                </td>
                                <td class="totalPrice${productStatus.index+1} price">
                                    <c:choose>
                                        <c:when test="${roleCode  eq 6}">${productVo.purchasePrice * productVo.sellerbAtchQuantity}</c:when>
                                        <c:when test="${roleCode  eq 3}">${productVo.settlementPrice * productVo.municipalBatchQuantity}</c:when>
                                    </c:choose>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </c:forEach>
        </div>
    </div>
    </form>
</div>

<div style="float: right;padding-top: 20px;padding-right: 20px;">
    <div>
        商品总金额<span id="priceView" style="color: red;">20000.00</span>元
    </div>
    <div style="float: right;padding-top: 20px;padding-right: 20px;">
        <button onclick="submit();">提交</button>
    </div>
</div>

<!--新增地址表单-->
<!--  弹出层开始  by  yyg -->
<div class="addr_form" id="addForm" style="display:none;">
    <form class="form-horizontal"  id="addressForm" style="margin-top: 40px;">
        <div class="form-group">
            <label for="contacts" class="col-sm-3 control-label"><i class="red">*</i>联系人:</label>
            <div class="col-sm-8">
                <input type="text" class="form-control validate[required, maxSize[20]]"   id="contacts" name="contacts"  placeholder="请输入联系人">
            </div>
        </div>
        <div class="form-group">
            <label for="phoneNo" class="col-sm-3 control-label"><i class="red">*</i>手机号:</label>
            <div class="col-sm-8">
                <input type="text" class="form-control validate[required,custom[phone],maxSize[11]]"  id="telPhone" name="telPhone" placeholder="请输入手机号">
            </div>
        </div>
        <div class="form-group">
            <label for="telPhone" class="col-sm-3 control-label">座机号:</label>
            <div class="col-sm-8">
                <input type="text" class="form-control " id=phoneNo    name="phoneNo" placeholder="请输入座机号">
            </div>
        </div>
        <div class="form-group">
             <label for="area_div" class="col-sm-4 control-label"><span style="color:red;">*</span>所属区域:</label>
		            <div id="area_div" style="width: 600px;height:27px;display:inline">
		      </div>
        </div>
        <div class="form-group">
            <label for="address" class="col-sm-3 control-label"><i class="red">*</i>详细地址:</label>
            <div class="col-sm-8">
                <input type="text" class="form-control validate[required, maxSize[500]]"  id="address"     name="address"  placeholder="请输入详细地址">
            </div>
        </div>
        <div class="form-group">
            <div class="edit_btn">
                <button type="button" class="btn btn-primary"    onclick="save();"  id="addAddress">新增</button>
                <button type="button" class="btn btn-danger" id="cancel">取消</button>
            </div>
        </div>
	<!--   隐藏域参数 by  yyg -->
         <input type="hidden"   id="type"  value=""   name="type"  />
         <input type="hidden"   id="positionId"   value=""  name="positionId"  />
  <!--   隐藏域参数 by  yyg --> 
    </form>
</div>
<!--  弹出层结束  by  yyg -->

<script src="${ctx}/static/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="${ctx}/static/plugins/datatables/jquery.dataTables.js" type="text/javascript"></script>
<script src="${ctx}/static/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<script src="${ctx}/static/plugins/layer/layer.js"></script>
<script src="${ctx}/static/js/common/area.js" type="text/javascript"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine-zh_CN.js"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine.js"></script>
	
<script type="text/javascript">
var openDiv;
$(function(){
	
	$("#addressForm").validationEngine({ 
		promptPosition: "topRight", 
		validationEventTriggers:"keyup blur", 
		success :  false,
		failure : function() { callFailFunction()  }
	});
	$("#cancel").click(function () {
	    close();
	});
	//计算商品总价
    getTotalPrice();
});

//区域select动态级联
areaAll({
    url: "${ctx}/api/merchant/getAllPosition",
	startFun:function(){
		$("#area_div").find(".formError").remove();
	},
	totalSelect:3,
    DivId: "area_div",
//     selectWidthArr: ["90px", "90px", "90px", "90px"],
    selectWidthArr: ["90px", "90px", "90px"],
//     areaArr: ["省份:","市:", "区县:","社区:"],
 	areaArr: ["省份:","市:", "区县:"],
//     idArr: ["provinceId", "cityId", "countyId","townId"],
 	idArr: ["provinceId", "cityId", "countyId"],
    isNeedName: false,
    spaceArrLeft:[5,5,5,5],
    spaceArrRight:[5,5,5,5],
    data: null,
    backFun: function(){
    	$("select[name='provinceId']").addClass("validate[required]");
    	$("select[name='cityId']").addClass("validate[required]");
    	$("select[name='countyId']").addClass("validate[required]");
//     	$("select[name='townId']").addClass("validate[required]");
    }
});
//关闭layer 弹出层
function close() {
    resetForm();
    layer.close(openDiv);
}

/*新增地址弹框*/
function  opneHiddenDiv(){
	var length=$("#addressUl").find("li").length;
	if(length>20){
		layer.alert('最多可以添加20个收货地址', {icon: 2,closeBtn: 0}); 
	}
	if(length==0){
		$("#type").val("1");
	}
	if($("#area_div").html()==""){
		areaAll({
            url: "${ctx}/api/merchant/getAllPosition",
			startFun:function(){
				$("#area_div").find(".formError").remove();
			},
			totalSelect:3,
		    DivId: "area_div",
//		     selectWidthArr: ["90px", "90px", "90px", "90px"],
		    selectWidthArr: ["90px", "90px", "90px"],
//		     areaArr: ["省份:","市:", "区县:","社区:"],
		 	areaArr: ["省份:","市:", "区县:"],
//		     idArr: ["provinceId", "cityId", "countyId","townId"],
		 	idArr: ["provinceId", "cityId", "countyId"],
		    isNeedName: false,
		    spaceArrLeft:[5,5,5,5],
		    spaceArrRight:[5,5,5,5],
		    data: null,
		    backFun: function(){
		    	$("select[name='provinceId']").addClass("validate[required]");
		    	$("select[name='cityId']").addClass("validate[required]");
		    	$("select[name='countyId']").addClass("validate[required]");
//		     	$("select[name='townId']").addClass("validate[required]");
		    }
		});
	}
	
	  openDiv = layer.open({
	        title: "新增地址",
	        type: 1,
	        closeBtn: 0,
	        resize: false,
	        skin: 'layui-layer-rim', //加上边框
	        area: ['945px', '500px'], //宽高
	        content: $("#addForm")
	    });
} 
//改变地址样式
function  change(id){
	    $("input[id='addressInput"+id+"'][name='address']").parent().parent().parent().siblings().removeClass("selected");
	    $("input[id='addressInput"+id+"'][name='address']").parent().parent().parent().addClass("selected");
}

//保存地址方法
function  save(){
	//表单验证
	 	var flag = $("#addressForm").validationEngine("validate");
		if(!flag){
	 		return false;
		} 
// 		if(!checkSelect()){
// 			return false;
// 		}
		$("#positionId").val($("select[name='countyId']").val());
		var poststr=$('#addressForm').serialize();
		$.ajax({url:'${ctx}/api/merchantBalanceAccounts/addAddress',data:poststr,dataType:"json",type:"post",success:savecallback,error:function(data){
					layer.alert("与服务器连接中断");
     }});
		
		
}
//成功回调方法
function savecallback(data){
			if(data.code=="200"){
				appendAddress(data.data);
				close();
			}else{
			if(data.code=="80004" )
			{  
				layer.msg(data.message, {icon: 2}); 
			}
			}
		}
//清空表单方法
function   resetForm(){
		$('#addressForm').find("input").val("");
		$('#addressForm').find("select").val("");
		$("#area_div").html("");
	}
//验证 select 是否选值
function   checkSelect(){
		var isGo=true;
		if($("select[name='provinceId']").val()==""){
			layer.alert('请选择省份', {icon: 2,closeBtn: 0}); 
			isGo=false;
			return  isGo;
		}
		if($("select[name='cityId']").val()==""){
			layer.alert('请选择市', {icon: 2,closeBtn: 0}); 
			isGo=false;
			return  isGo;
		}
		if($("select[name='countyId']").val()==""){
			layer.alert('请选择区县', {icon: 2,closeBtn: 0}); 
			isGo=false;
			return  isGo;
		}
		return  isGo;
	}
//添加成功 追加新的地址到#addressUl下
function   appendAddress(data){
		var length=$("#addressUl").find("li").length;
		var html="";
		html+="<li class='address-wrap selected'>";
		html+="<div class='addressBox'>";
		html+="<label class='addressInfo' for='addressInput"+data.id+"'>";
		html+="<input class='radioSelect' onclick='change("+data.id+");' value='"+data.id+"' name='address' id='addressInput"+data.id+"'  type='radio'>";
		html+="<span class='user-address'>";
		html+="<span>"+data.provinceName+"&nbsp;&nbsp;"+data.cityName+"&nbsp;&nbsp;"+data.areaName+"</span>";
		html+="<span>"+data.address+"</span>";
	    html+="<span>（</span>";
		html+="<span>"+data.contacts+"</span>";
		html+="<span> 收）</span>";
	    html+="<em>"+data.telPhone+"</em>";
		html+="</span>";
		html+="</label>";
		html+="</div>";
		html+="</li>";
		$("#addressUl").append(html);
		//选中当前添加的地址
				$("input[name='address'][id='addressInput"+data.id+"']").attr("checked",true);
				$("input[id='addressInput"+data.id+"'][name='address']").parent().parent().parent().siblings().removeClass("selected");
			    $("input[id='addressInput"+data.id+"'][name='address']").parent().parent().parent().addClass("selected");
						
	}
/***********************************************************朋朋你接着写吧！加油！***************************************************************/

    //制保留2位小数，如：2，会在2后面补上00.即2.00
    function toDecimal(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return false;
        }
        var f = Math.round(x*100)/100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return s;
    }
    //新增数量
    function addCount(max,tableId,totalPriceClass,countClass,price) {
        var input = '#' + tableId + ' .' + countClass;
        var currentCountInput = $(input);
        var currentCount = parseInt(currentCountInput.val());
        var count = currentCount+1;
        if (count >  max) {
            return;
        }
        currentCountInput.val(count);
        var priceText = '#' + tableId + ' .' + totalPriceClass
        $(priceText).text(toDecimal(count*price));
        //计算商品总价
        getTotalPrice();
    }
    //删除数量
    function removeCount(min,tableId,totalPriceClass,countClass,price) {
        var input = "#" + tableId + " ." + countClass;
        var currentCountInput = $(input);
        var currentCount = parseInt(currentCountInput.val());
        var count = currentCount-1;
        if (count < min) {
            return;
        }
        currentCountInput.val(count);
        var priceText = "#" + tableId + " ." + totalPriceClass;
        $(priceText).text(toDecimal(count*price));
        //计算商品总价
        getTotalPrice();
    }
    //校验数量
    function validateCount(min,max,This,tableId,totalPriceClass,price) {
        var currentCount = parseInt($(This).val());
        if (currentCount > max) {
            currentCount = max;
            $(This).val(max);
        }
        if (!currentCount || currentCount < min) {
            currentCount = min;
            $(This).val(min);
        }

        var priceText = "#" + tableId + " ." + totalPriceClass;
        $(priceText).text(toDecimal(currentCount*price));
        //计算商品总价
        getTotalPrice();
    }
    //计算商品总价
    function getTotalPrice() {
        var total = 0;
        $(".price").each(function(){
            total += parseFloat($(this).text());
        });
        $('#priceView').text(toDecimal(total));
    }
    //订单提交
    function submit() {
        //地址id
        var shippingAddressId;
        //联系人
        var contacts;
        //联系电话
        var telPhone
        //详细地址
        var address="";
        var addressLabel = $("input[type='radio']:checked");
        if (addressLabel.length <= 0) {
            alert("请选择收货地址");
            return;
        }

        shippingAddressId = addressLabel.val();
        addressLabel.siblings('.user-address').children().each(function(i,item) {
            if (i == 0 || i == 1) {
                address += $(item).text();
            }
            if (i == 3) {
                contacts = $(item).text();
            }
            if (i == 5) {
                telPhone = $(item).text();
            }

        });
        address = address.replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"");
        var productOrderDTOList = new Array();
        $("table").each(function(i,item) {
            var ProductOrderDTO = {};
            ProductOrderDTO.address = address;
            ProductOrderDTO.shippingAddressId = shippingAddressId;
            ProductOrderDTO.contacts = contacts;
            ProductOrderDTO.telPhone = telPhone;
            //供应商id
            ProductOrderDTO.supplerId = $(item).find(".supplierId").val();
            //商品信息
            var productDTOList = new Array();
            $(item).find("tbody tr" ).each(function() {
                var productDTO = {};
                $(this).find("td").each(function(j,td) {
                    if (j == 0) {
                        /** 商品id */
                        productDTO.productId = $(td).find("input").val();
                    }
                    if (j == 1) {
                        /** 商品名称 */
                        productDTO.productName = $(td).text();
                    }
                    if(j == 2) {
                        /** 商品编码 */
                        productDTO.productCode = $(td).text();
                    }
                    if(j == 4) {
                        /** 数量 */
                        productDTO.num = $(td).find("input").val();
                    }
                    if(j == 5) {
                        /** 单价(商品表的进货价) */
                        productDTO.purchasePrice = $(td).text();
                    }
                });
                productDTOList.push(productDTO);
            });
            ProductOrderDTO.productDTOList = productDTOList;
            productOrderDTOList.push(ProductOrderDTO);
        });
        orderSubmit(productOrderDTOList);
    }
    
    function orderSubmit(addOrder) {
        var json={
            'productOrderDTOList':addOrder
        };
        var data=JSON.stringify(json);
        console.info(data);
        $.ajax({
            async:false,
            url:"${ctx}/api/merchantBalanceAccounts/addOrder",
            data:data,
            type:"POST",
            dataType:"json",
            contentType : 'application/json;charset=utf-8', //设置请求头信息
            success:function(data){
                if(data.code =="200"){
                    if (data.data == "1") {
                        window.location.href = "${ctx}/api/merchantOrder/list?ide=1";
                    } else if (data.data == "2") {
                        window.location.href = "${ctx}/api/agentOrder/list?ide=1";
                    }


                }else{
                    alert(data.message);
                }
            }
        });
    }


</script>
</body>
</html>